<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;padding: 0;
        }
        #box{
            width: 300px;height: 300px;background: #ccc;position: absolute;
        }
    </style>
</head>
<body>
    <div id="box"></div>
</body>
<script>
    // 获取元素
    var obox=document.getElementById("box");
    obox.onmousedown=function(){
        console.log(1)
    }
    // 绑定事件
    obox.onmousedown=function(eve){
        // console.log(1)
        var e=eve||window.event;
        // 记录鼠标和被拖拽物体的相对位置
        var offsetX=e.clientX-obox.offsetLeft;
        var offsetY=e.clientY-obox.offsetTop;
        // 被拖拽物体保持相对距离跟鼠标移动
        document.onmousemove=function(eve){
            var e=eve||window.event;
            var l=e.clientX-offsetX;
            var t=e.clientY-offsetY;
            // 限制左右出界
            if(l<=0) l=0;
            // 获取当前浏览器的窗口宽度
            var windowWidth=document.documentElement.clientWidth||document.body.clientWidth;
            if(l>=windowWidth-obox.offsetWidth){
                l=windowWidth-obox.offsetWidth
            }
            // 限制上下出街
            if(t<=0) t=0;
            // 获取当前浏览器窗口的高
            var windowHeight=document.documentElement.clientHeight||document.body.clientHeight;
            if(t>=windowHeight-obox.offsetHeight){
                t=windowHeight-obox.offsetHeight
            }
            obox.style.left=l+'px';
            obox.style.top=t+'px';
        }
    }
    document.onmouseup=function(){
        document.onmousemove=null;
    }
</script>
</html>